<template>
  <div ref="chartRef" :style="{ width: width, height: height }"></div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref, watch } from "vue";
import * as echarts from "echarts";

export default defineComponent({
  name: "ECharts",
  props: {
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "400px",
    },
    options: {
      type: Object,
      required: true,
    },
  },
  setup(props) {
    const chartRef = ref<HTMLDivElement | null>(null);
    let chart: echarts.ECharts | null = null;

    const initChart = () => {
      if (chartRef.value) {
        chart = echarts.init(chartRef.value);
        chart.setOption(props.options);
      }
    };

    const updateChart = () => {
      if (chart) {
        chart.setOption(props.options);
      }
    };

    onMounted(() => {
      initChart();
    });

    watch(
      () => props.options,
      () => {
        updateChart();
      },
      { deep: true }
    );

    return {
      chartRef,
    };
  },
});
</script>
